package com.example.finalassessment.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.finalassessment.dao.UserMapper;
import com.example.finalassessment.model.Product;
import com.example.finalassessment.model.User;
import com.example.finalassessment.service.IUserService;
import com.example.finalassessment.util.ExceptionCodeMsgEnum;
import com.example.finalassessment.util.ResponseData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author funny_chao
 * @since 2024-12-09
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private UserMapper userMapper;
    @GetMapping("/all")//获取用户列表，分页
    public ResponseEntity<ResponseData> getAllUser(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "5") Integer size) {

        // 创建 Page 对象，设置当前页和每页显示的数量
        Page<User> userPage = new Page<>(page, size);

        // 查询分页数据
        Page<User> resultPage = userService.page(userPage);

        // 返回分页数据
        return ResponseEntity.ok(ResponseData.success(resultPage));
    }
    @PostMapping("/register")//注册
    public ResponseData register(@RequestBody User user) {
        try {
            boolean success = userService.doRegister(user);
            if (success) {
                return ResponseData.success("注册成功", null);
            } else {
                return ResponseData.error(ExceptionCodeMsgEnum.CONTENT_NOT_EXIST);
            }
        } catch (RuntimeException e) {
            // 检查异常消息以确定具体的错误类型
            if (e.getMessage().equals(ExceptionCodeMsgEnum.USERNAME_ALREADY_EXISTS.getMessage())) {
                return ResponseData.error(ExceptionCodeMsgEnum.USERNAME_ALREADY_EXISTS);
            } else {
                System.out.println(e);
                return ResponseData.error(ExceptionCodeMsgEnum.SERVER_ERROR);
            }
        }
    }
    @PostMapping("/login")//登录
    public ResponseData login(@RequestBody User user) {
        try {
            String token = userService.doLogin(user);

            // 查询用户信息以确保返回完整的用户数据
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            User user1 = userMapper.selectOne(queryWrapper.eq("username", user.getUsername()));

            // 将用户数据添加到响应中
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token);
            responseData.put("username", user1.getUsername());
            responseData.put("userId", user1.getId());
            responseData.put("level", user1.getLevel());// 确保返回了userId

            System.out.println("返回的数据" + responseData);
            System.out.println(ResponseData.success("登录成功", responseData));
//            return ResponseEntity.ok(ResponseData.success("登录成功", responseData));
            return ResponseData.success("登录成功", responseData);
        } catch (RuntimeException e) {
            // 检查异常消息以确定具体的错误类型
            if (e.getMessage().equals(ExceptionCodeMsgEnum.INVALID_USERNAME_OR_PASSWORD.getMessage())) {
                System.out.println("账号密码错误");
                return ResponseData.error(ExceptionCodeMsgEnum.INVALID_USERNAME_OR_PASSWORD);
            } else {
                System.out.println(e);
                return ResponseData.error(ExceptionCodeMsgEnum.SERVER_ERROR);
            }
        }
    }

    @GetMapping("/id/{id}")
    public ResponseData getUserById(@PathVariable Integer id) {
        User user = userService.getById(id); // 获取用户数据
        if (user == null) {
            return ResponseData.error(ExceptionCodeMsgEnum.PRODUCT_NOT_FOUND);
        }
        return ResponseData.success(user); // 返回用户数据
    }


    // 添加新商品
    @PostMapping("/add")//管理员添加用户
    public ResponseEntity<ResponseData> addUser(@RequestBody User user) {
        ResponseData responseData = userService.addUser(user);
        return ResponseEntity.ok(responseData);
    }

    // 更新商品信息
    @PostMapping("/edit/{id}")//管理员修改用户基本信息
    public ResponseData updateUser(@PathVariable Integer id, @RequestBody User user) {
        user.setId(id);
        return userService.editUser(id,user);
    }

    @PostMapping("/update")//更新个人信息
    public ResponseData updateUser(@RequestBody User user) {
        // 保存用户信息，包括 profile 图片
        return userService.updateUser(user);
    }

    @DeleteMapping("/delete/{id}")//删除个人
    public ResponseData deleteuser(@PathVariable Integer id) {
        return userService.deleteUser(id);
    }

    @GetMapping("/count")//查询用户性别数据，用于制图
    public ResponseData getUserCountPerDay() {
        return userService.getUserCountPerDay();  // 调用 Service 查询数据
    }

}
